package edu.ccut.saturn.basecomponent.database.preparedstatement;

import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public abstract class PreparedStatementSetUtils {

	private static Map<String, IPreparedStatementSet> sets = new HashMap<String, IPreparedStatementSet>();

	private static final String SET_FILE_PATH = "set.properties";
	
	private static final String DEFAULT_TYPE = "OBJECT";

	static {
		initalSets();
	}

	@SuppressWarnings("unchecked")
	private static void initalSets() {
		
		Properties properties = new Properties();
		
		InputStream inputStream = null;
		
		inputStream = PreparedStatementSetUtils.class.getResourceAsStream(SET_FILE_PATH);
		try {
			properties.load(inputStream);
			
			Enumeration keys = properties.keys();
			
			while (keys.hasMoreElements()) {
				String key = (String)keys.nextElement();
				String value = properties.getProperty(key);
				
				sets.put(key, (IPreparedStatementSet)Class.forName(value).newInstance());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void setValue(String typeKey, PreparedStatement statement, int i, Object value) throws SQLException {
		IPreparedStatementSet preparedStatementSet = sets.get(typeKey.toUpperCase());
		if(preparedStatementSet == null){
			preparedStatementSet = sets.get(DEFAULT_TYPE);
		}
		preparedStatementSet.setValue(statement, i, value);
	}
}
